package quinn.web.util;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class XmlDom4jParse {
	HashMap xmlConf = null;
	public XmlDom4jParse(String path) {         
		xmlConf = (HashMap) parseXml(path);
		System.out.println(xmlConf);
	}
	
	private Map parseXml(String path) {
        try {
        	SAXReader reader = new SAXReader(); 
			Document  document = reader.read(new File(path));
			Element root = document.getRootElement();
			return iteratorNode(root);
			
		} catch (DocumentException e) {
			e.printStackTrace();
			return null;
		} 
	}
	
	private HashMap iteratorNode(Element root) {
		HashMap all = new HashMap();
		HashMap node = new HashMap();
		for(Iterator it=root.elementIterator();it.hasNext();){ 
	        Element element = (Element) it.next();
	        if(element.elements().size()>0) {
	        	HashMap childnodeInfo = iteratorNode(element);
	        	node.put(element.attributeValue("name"), childnodeInfo.get(element.getName()));
	        }else {
	        	node.put(element.getName(), element.getText());
	        }
	        all.put(root.getName(), node);
		}
		return all;
	}
	
	public List getAllPcName() {
		ArrayList<String> pcName = new ArrayList<String>();
		HashMap pc = (HashMap) xmlConf.get("PC");
		Iterator iter = pc.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			Object key = entry.getKey();
			HashMap value = (HashMap)entry.getValue();
			if(!value.get("TYPE").toString().toUpperCase().equals("MASTER")) {
				pcName.add((String) key);
			}
		}
		return pcName;
	}
	
	public Map getPcConfByName(String pcName) {
		HashMap pc = (HashMap) xmlConf.get("PC");
		Iterator iter = pc.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			Object key = entry.getKey();
			if (pcName.equals((String) key)) {
				return (Map) entry.getValue();
			}
		}
		return null;
	}
	
	public static void main(String[] args) {
		XmlDom4jParse xmlDom4jParse = new XmlDom4jParse("PcInfo.xml");
		System.out.println(xmlDom4jParse.getAllPcName());
		System.out.println(xmlDom4jParse.getPcConfByName("pi"));
	}

}
